package com.yyp.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yyp.dao.BaseDao;

@Service
@Transactional
public class BaseDaoImpl implements BaseDao {
	@Resource
	SessionFactory factory;

	/**
	 * 保存数据到数据库
	 * 
	 * @param <T>
	 * @param entity
	 *            传过来得实体类对象
	 */
	public void save(Object entity) {
		factory.getCurrentSession().merge(entity);

	}

	/**
	 * 删除
	 * 
	 * @param <T>
	 * @param entity
	 *            传过来得实体类对象
	 * @param names
	 *            按关键名词删除
	 */
	public <T> void delete(Class<T> entity, Serializable names) {
		factory.getCurrentSession().delete(
				factory.getCurrentSession().load(entity, names));
	}

	/**
	 * 查找
	 * 
	 * @param <T>
	 * @param entity
	 *            传过来得实体类对象
	 * @param name
	 *            按关键名词查找
	 * @return
	 */
	public <T> T find(String sql, String name[]) {
		Query query = factory.getCurrentSession().createQuery(sql);
		for (int i = 0; i < name.length; i++) {
			query.setString(i, name[i]);
		}
		return (T) query.uniqueResult();
	}

	public <T> List<T> findAll(String sql) {
		Query query = factory.getCurrentSession().createQuery(sql);
		return query.list();
	}

	/**
	 * 查找
	 * 
	 * @param <T>
	 * @param entity
	 *            传过来得实体类对象
	 * @param id
	 *            按ID查找
	 * @return
	 */
	public <T> T find(Class<T> entity, Integer id) {
		return (T) factory.getCurrentSession().get(entity, id);
	}

	/**
	 * 更新
	 * 
	 * @param <T>
	 * @param entity
	 *            传过来得实体类对象
	 */
	public void updata(Object entity) {
		factory.getCurrentSession().update(entity);
	}

}
